<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of AccessFilter
 *
 * @author Administrator
 */

namespace yii\filters\auth;

use Yii;
use yii\base\ActionFilter;

/*
 * 访问控制
 */

class AccessFilter extends AuthMethod {

    public $tokenParam = 'access-token';

    public function authenticate($user, $request, $response) {
        $accessToken = $request->get($this->tokenParam);
        if (is_string($accessToken)) {
            $identity = $user->loginByAccessToken($accessToken, get_class($this));
            if ($identity) {
                $userIp = Yii::$app->request->userIP;
                $now_time = strtotime('now');
                $last_login_time = $identity->last_login_time;
                $diff_time = $now_time - strtotime($last_login_time);
                /**
                 * check ip and time
                 */
                if ($userIp == $identity->last_login_ip) {
                    if ($diff_time < Yii::$app->params['restapi']['tokenExpire']) {
                        return $identity;
                    } else {
                        throw new UnauthorizedHttpException(Yii::t('yii', 'You are requesting with an expired access token, please request for a new one.'));
                    }
                } else {
                    throw new UnauthorizedHttpException(Yii::t('yii', 'You are requesting with an access token with a different ip address.'));
                }
            } else {
                $this->handleFailure($response);
            }
        } else {
            throw new UnauthorizedHttpException(Yii::t('yii', 'You are requesting with a wrong-formatted access token.'));
        }
        if ($accessToken !== null) {
            $this->handleFailure($response);
        }

        return null;
    }

}
